# -*- coding: utf-8 -*-
# @author okumura@laurus.co.jp

from gaeo.controller import BaseController
from libs.laurus.action import before_action
from google.appengine.ext.webapp.util import login_required
from google.appengine.api import mail
from model.pigeon import Pigeon
from model.pigeonto import Pigeonto
from datetime import datetime
from libs.django.core.paginator import QuerySetPaginator, InvalidPage, EmptyPage

class InboxController(BaseController):
    def before_action(self):
        before_action(self)

    @login_required
    def index(self):
        query = Pigeonto.all()
        query.filter('to_user =', self.user)
        query.filter('status =', 'Sent')
        query.order('-post_at')
        paginator = QuerySetPaginator(query, 20)

        if self.params.get('page'):
            page = int(self.params.get('page'))
        else:
            page = 1

        try:
            self.pigeontos = paginator.page(page)
        except (EmptyPage, InvalidPage):
            self.pigeontos = paginator.page(paginator.num_pages)


    @login_required
    def detail(self):
        #IDが指定されていなければリダイレクト
        if not self.params.get('id'):
            self.redirect('/')
            return
        #伝書鳩が取得できなければリダイレクト
        pigeon = Pigeon.get_by_id(int(self.params.get('id')))
        if not pigeon:
            self.redirect('/')
            return
        #宛先にcurrent_userがなければリダイレクト
        pigeonto = None
        for to in pigeon.pigeontos:
            if to.to_user == self.user:
                pigeonto = to
                break
        if not pigeonto:
            selr.redirect('/inbox')
            return
        #テンプレートに登録
        self.pigeon = pigeon

        if not pigeonto.read_at:
            #閲覧フラグの更新
            pigeonto.read_at = datetime.now()
            pigeonto.put()
            #閲覧通知の送信
            if pigeon.read_info:
                mail.send_mail(
                    self.user.email(),
                    pigeon.from_user.email(),
                    u'[伝書鳩]見ました「%s」' % pigeon.subject,
                    """
%s<%s>様が「%s」を閲覧しました
""" % (self.user.nickname(),self.user.email(),pigeon.subject)
                )

